package com.xbfinal.core;

import com.xbfinal.utils.Constant;

import java.util.concurrent.atomic.LongAdder;

/**
 * @version 1.0
 * @Author 笑霸final
 * @Date 2023/10/18 20:16
 * @注释 下载显示进度
 */
public class DownloaderInfo implements Runnable{
    //下载文件总大小
    private long httpFileContentLength;

    //本地已经下载的大小 多个线程下载可能有线程安全问题 需要用原子类
    public static LongAdder finishedSize = new LongAdder();

    //前一次下载大小
    public  double proDownSize;

    //本次下载大小
    public static volatile LongAdder downSize = new LongAdder();

    public DownloaderInfo() {}
    public DownloaderInfo(long httpFileContentLength) {
        this.httpFileContentLength = httpFileContentLength;
    }

    @Override
    public void run() {

        //计算文件总大小 单位是M
        String downFileSize = String.format("%.2f",httpFileContentLength/ Constant.MB);

        //计算每秒下载速度KB
        int speed = (int)((downSize.doubleValue()-proDownSize) / 1024d);

        proDownSize= downSize.doubleValue();

        //剩余文件大小
        double remainSize = httpFileContentLength - finishedSize.doubleValue() - downSize.doubleValue();

        //计算剩余时间
        double rTime = remainSize / 1024 / speed;
        String remainTime = String.format("%.1f", rTime);
        if("Infinity".equals(remainTime)){
            remainTime = "————";
        }
        //已经下载大小
        String currentFileSize = String.format("%.2f", ((downSize.doubleValue() - finishedSize.doubleValue()) / Constant.MB));
        String downInfo = String.format("下载进度：%s mb / %s mb ==== 速度：%s kb/s ====剩余时间 %s 秒",
                currentFileSize, downFileSize, speed, remainTime);
        System.out.print("\r");
        System.out.print(downInfo);


    }
}
